package com.app.twth.ui.finalprocess.trk;


import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.app.twth.BR;
import com.app.twth.R;
import com.app.twth.app.AppRouter;
import com.app.twth.app.Constant;
import com.app.twth.base.BaseActivity;
import com.app.twth.databinding.ActivityFinalprocessTrkBinding;
import com.app.twth.databinding.DialogSkuMultipleHintBinding;
import com.app.twth.ui.finalprocess.FinalProcess;
import com.app.twth.ui.finalprocess.FinalProcessQr;
import com.app.twth.ui.finalprocess.FinalProcessViewModel;
import com.app.twth.ui.finalprocess.rp.FinalProcessRPActivity;
import com.app.twth.ui.finalprocess.submit.FinalProcessSubmitActivity;
import com.app.twth.utils.DividerItemDecoration;
import com.app.twth.utils.EditTextUtil;
import com.app.twth.utils.MyDialogUtil;
import com.app.twth.utils.ToastUtil;
import com.app.twth.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * @describe :
 */
public class FinalProcessTrkActivity extends BaseActivity<ActivityFinalprocessTrkBinding, FinalProcessViewModel> {
    private String TAG = getClass().getSimpleName();
    private int type = 0;
    private String batchNo;
    private String oldIbLpn;
    private FinalProcessTrkAdapter adapter;
    private List<FinalProcess.ItemInfoDTO> finalProcessLpnList = new ArrayList<>();

    @Override
    protected void initListener() {
        viewModel.trackingLiveData.observe(this, data -> {
            if (data == null) {
                binding.tvCode.requestFocus();
                return;
            }

            if (Utils.isEmpty(data.getSku())) {
                binding.tvCodeSku.setText("");
                binding.tvCodeSku.requestFocus();
            } else {
                binding.tvCodeSku.setText(data.getSku());
                binding.tvQty.requestFocus();
            }
        });
        viewModel.errorResultCode.observe(this, code -> {
            showHint((String) code);
        });
        viewModel.isLoading.observe(this, b -> {
            if (b.isShow()) {
                showProgressDialog(b.getMsg());
            } else {
                dismissProgressDialog();
            }
        });
    }

    protected String setTitle() {
        return "FinalProcess(TRK#)";
    }

    @Override
    protected int initViewModelId() {
        return BR.viewModel;
    }

    @Override
    protected void initData() {
        setNext("");
        Bundle bundle = getIntent().getBundleExtra(AppRouter.K_EXTRA);
        FinalProcess finalProcess = (FinalProcess) bundle.getSerializable("FinalProcess");
        batchNo = finalProcess.getItemInfo().getBatchNo();
        oldIbLpn = finalProcess.getItemInfo().getIbLpn();
        finalProcessLpnList = finalProcess.getIbLpnItemList();

        binding.tvBatchNo.setText(batchNo);
        binding.tvOriginalLpn.setText(oldIbLpn);

        binding.tvCode.requestFocus();
        binding.tvCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                binding.tvCodeSku.setText("");
                binding.tvQty.setText("0");
            }
        });
        binding.tvCode.setOnEditorActionListener(EnterListenter);
        binding.tvCode.setOnFocusChangeListener(onFocusChangeListener);
        binding.tvCodeSku.setOnFocusChangeListener(onFocusChangeListener);
        binding.tvQty.setOnFocusChangeListener(onFocusChangeListener);

        adapter = new FinalProcessTrkAdapter(this, finalProcessLpnList, position -> {
            if (finalProcessLpnList.size() <= position) {
                return;
            }
            FinalProcess.ItemInfoDTO finalProcessLpn = finalProcessLpnList.get(position);
            binding.tvCode.setText(finalProcessLpn.getTrackingCode());
            viewModel.returnFinalProcessInfo(finalProcessLpn.getId());
        });
        binding.recyclerview.setHasFixedSize(true);
        binding.recyclerview.setItemAnimator(new DefaultItemAnimator());

        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerview.setLayoutManager(layoutManager1);
        //添加装饰类
        binding.recyclerview.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL_LIST));
        binding.recyclerview.setAdapter(adapter);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        bottomLayoutBinding.tvHint.setText("");
        initScan();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unScan();
    }

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_scan:
                binding.tvCode.requestFocus();
                setScan();
                break;
            case R.id.iv_scan_barcode:
                binding.tvCodeSku.requestFocus();
                setScan();
                break;
            case R.id.iv_scan_barcode_qty:
                binding.tvQty.requestFocus();
                setScan();
                break;
            case R.id.iv_qty:
                String cartonsQty = binding.tvQty.getText().toString();
                if (Utils.isEmpty(cartonsQty)) {
                } else if (Integer.parseInt(cartonsQty) > 1) {
                    binding.tvQty.setText((Integer.parseInt(cartonsQty) - 1) + "");
                } else {
                    binding.tvQty.setText("0");
                }
                break;
            case R.id.tv_reset:
                binding.tvCode.requestFocus();
                binding.tvCode.setText("");
                binding.tvCodeSku.setText("");
                binding.tvQty.setText("0");
                bottomLayoutBinding.tvHint.setText("");
                break;
            case R.id.tv_next:
                if (System.currentTimeMillis() - timeMillis < spaceTime) {//两秒内触发一次
                    return;
                }
                timeMillis = System.currentTimeMillis();
                String tracking = binding.tvCode.getText().toString();
                if (Utils.isEmpty(tracking)) {
                    ToastUtil.showToast("Please input  trk#");
                    return;
                }
                if (viewModel.trackingLiveData.getValue() == null) {
                    searchTrk(tracking);
                }
                //                determineType();

                String qtyStr = binding.tvQty.getText().toString();
                if (Utils.isEmpty(qtyStr)) {
                    ToastUtil.showToast("Please input quantity");
                    return;
                }
                qty = Integer.parseInt(qtyStr);
                Log.e(TAG, "(" + qty + ")");

                if (qty != viewModel.trackingLiveData.getValue().getQty()) {
                    ToastUtil.showToast("errro：exceed QTY");
                    return;
                }
                setNext();
                break;
        }
    }

    private View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                switch (v.getId()) {
                    case R.id.tv_code:
                        type = 0;
                        break;
                    case R.id.tv_code_sku:
                        type = 1;
                        break;
                    case R.id.tv_qty:
                        type = 2;
                        break;
                }
            } else {
                type = 0;
            }
        }
    };
    private TextView.OnEditorActionListener EnterListenter = new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                barcodeStr = binding.tvCode.getText().toString();
                EditTextUtil.hideInput(mContext);

                if (Utils.isEmpty(barcodeStr)) {
                    return false;
                }
                searchTrk(barcodeStr);
            }
            return false;
        }
    };

    @Override
    public void getScanninCode() {
        super.getScanninCode();
        switch (type) {
            case 0:
                binding.tvCode.setText(barcodeStr);

                searchTrk(barcodeStr);
                break;
            case 1:
                if (viewModel.trackingLiveData.getValue() == null) {
                    binding.tvCodeSku.setText("");
                    mVibrator.vibrate(new long[]{0, 1000}, -1);
                    return;
                }
                if (Utils.isEmpty(viewModel.trackingLiveData.getValue().getSku())) {
                    binding.tvCodeSku.setText("");
                    mVibrator.vibrate(new long[]{0, 1000}, -1);
                    return;
                }
                if (viewModel.trackingLiveData.getValue().getSku().equalsIgnoreCase(barcodeStr)) {//扫SKU
                    binding.tvCodeSku.setText(barcodeStr);
                    binding.tvQty.setText(1 + "");
                    binding.tvQty.requestFocus();
                    return;
                }
                if ((viewModel.trackingLiveData.getValue().getBarcodeList() == null) || (viewModel.trackingLiveData.getValue().getBarcodeList().size() == 0)) {
                    binding.tvCodeSku.setText("");
                    mVibrator.vibrate(new long[]{0, 1000}, -1);
                    return;
                }
                for (String barcodes : viewModel.trackingLiveData.getValue().getBarcodeList()) {
                    if (barcodes.equalsIgnoreCase(barcodeStr)) {//扫barcode
                        binding.tvCodeSku.setText(barcodeStr);
                        binding.tvQty.setText(1 + "");
                        binding.tvQty.requestFocus();
                        return;
                    }
                }

                binding.tvCodeSku.setText("");
                mVibrator.vibrate(new long[]{0, 1000}, -1);
                break;
            case 2:
                try {
                    String barCode = binding.tvCodeSku.getText().toString();
                    if (Utils.isEmpty(barCode)) {
                        mVibrator.vibrate(new long[]{0, 1000}, -1);
                        return;
                    }
                    Log.e(TAG, "barCode:" + barCode);
                    Log.e(TAG, "barcodeStr:" + barcodeStr);
                    if (barCode.equalsIgnoreCase(barcodeStr)) {
                        String qty = binding.tvQty.getText().toString();
                        if (Utils.isEmpty(qty)) {
                            binding.tvQty.setText(1 + "");
                        } else {
                            binding.tvQty.setText((1 + Integer.parseInt(qty)) + "");
                        }
                    } else {
                        if ((viewModel.trackingLiveData.getValue().getBarcodeList() == null) || (viewModel.trackingLiveData.getValue().getBarcodeList().size() == 0)) {
                            mVibrator.vibrate(new long[]{0, 1000}, -1);
                            return;
                        }

                        for (String barcodes : viewModel.trackingLiveData.getValue().getBarcodeList()) {
                            if (barcodes.equalsIgnoreCase(barcodeStr)) {//扫barcode
                                String qty = binding.tvQty.getText().toString();
                                if (Utils.isEmpty(qty)) {
                                    binding.tvQty.setText(1 + "");
                                } else {
                                    binding.tvQty.setText((1 + Integer.parseInt(qty)) + "");
                                }
                                return;
                            }
                        }
                        mVibrator.vibrate(new long[]{0, 1000}, -1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void searchTrk(String value) {
        boolean isExist = false;
        for (int i = 0; i < finalProcessLpnList.size(); i++) {
            FinalProcess.ItemInfoDTO finalProcessLpnTemp = finalProcessLpnList.get(i);
            if (finalProcessLpnTemp.getTrackingCode().equalsIgnoreCase(value)) {
                isExist = true;
                viewModel.returnFinalProcessInfo(finalProcessLpnTemp.getId());
                i = finalProcessLpnList.size();
            }
        }
        if (!isExist) {
            bottomLayoutBinding.tvHint.setText("Invalid TRK# number");
        }
    }


    //判断类型
    private void determineType() {
        String hint = "";
        switch (viewModel.trackingLiveData.getValue().getType()) {
            case 1:
                hint = "please put it in a new inboundLPN,then putaway and destroy." + (viewModel.trackingLiveData.getValue().getAccountId() != 0 ? (" LPN include ID：" + viewModel.trackingLiveData.getValue().getAccountId()) : "") + "";
                break;
            case 2:
                hint = "please put it in a new inboundLPN,then putaway and destroy." + (viewModel.trackingLiveData.getValue().getAccountId() != 0 ? (" LPN include ID：" + viewModel.trackingLiveData.getValue().getAccountId()) : "") + "";
                break;
            case 3:
                hint = "please put it in a new inboundlpn ，and then putaway.";
                break;
            case 4:
                hint = "Need to return it to customer，Please put it in inbound lpn. Waiting for customers to pick it" + (viewModel.trackingLiveData.getValue().getAccountId() != 0 ? (" , LPN include ID：" + viewModel.trackingLiveData.getValue().getAccountId()) : "") + ".";
                break;
            case 5:
                hint = "please redo PreProcess for it！Keep it in the original inbound lpn";
                break;
        }

        showTypeDialog(hint);
    }

    private AlertDialog dialogType;

    private void showTypeDialog(String content) {
        dialogType = MyDialogUtil.getDialog(mContext, initTypeDialogView(content), Gravity.CENTER);
        dialogType.setCanceledOnTouchOutside(true);
        dialogType.show();
    }

    private View initTypeDialogView(String content) {
        DialogSkuMultipleHintBinding dialogBinding = DialogSkuMultipleHintBinding.inflate(getLayoutInflater());
        dialogBinding.tvTitle.setText("Tips");
        dialogBinding.tvContent.setText(content);

        if (viewModel.trackingLiveData.getValue().getType() == 5) {//重新拍照

            if (!Utils.isEmpty(viewModel.trackingLiveData.getValue().getNotes())) {
                dialogBinding.tvNotes.setText(viewModel.trackingLiveData.getValue().getNotes());
                dialogBinding.layoutNotes.setVisibility(View.VISIBLE);
            }

            dialogBinding.tvConfirm.setText("  OK  ");
        }
        dialogBinding.tvCancel.setOnClickListener(v -> {
            if (dialogType != null) {
                dialogType.dismiss();
            }
        });

        dialogBinding.tvConfirm.setOnClickListener(v -> {
            if (dialogType != null) {
                dialogType.dismiss();
            }
            String qtyStr = binding.tvQty.getText().toString();
            if (Utils.isEmpty(qtyStr)) {
                ToastUtil.showToast("Please input quantity");
                return;
            }
            qty = Integer.parseInt(qtyStr);
            Log.e(TAG, "(" + qty + ")");

            if (qty != viewModel.trackingLiveData.getValue().getQty()) {
                ToastUtil.showToast("Please enter the correct quantity");
                return;
            }
            setNext();
        });
        return dialogBinding.getRoot();
    }

    int qty;

    private void setNext() {
        FinalProcessQr finalProcessQr = new FinalProcessQr();
        finalProcessQr.setBatchNo(batchNo);
        finalProcessQr.setOldIbLpn(oldIbLpn);
        finalProcessQr.setId(viewModel.trackingLiveData.getValue().getId() + "");
        finalProcessQr.setSku(viewModel.trackingLiveData.getValue().getSku());
        finalProcessQr.setNewSku(viewModel.trackingLiveData.getValue().getNewSku());
        finalProcessQr.setTrackingCode(viewModel.trackingLiveData.getValue().getTrackingCode());
        finalProcessQr.setAccountId(viewModel.trackingLiveData.getValue().getAccountId());
        finalProcessQr.setType(viewModel.trackingLiveData.getValue().getType());
        finalProcessQr.setQty(qty);

        if (viewModel.trackingLiveData.getValue().getType() == 4) {//重新拍照
            Bundle bundle = new Bundle();
            bundle.putSerializable("FinalProcessQr", finalProcessQr);
            AppRouter.showActivityForResult(mContext, FinalProcessRPActivity.class, bundle, Constant.ForResult2);
            return;
        }

        Bundle bundle = new Bundle();
        bundle.putSerializable("FinalProcessQr", finalProcessQr);
        AppRouter.showActivityForResult(mContext, FinalProcessSubmitActivity.class, bundle, Constant.ForResult2);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.ForResult2 && resultCode == RESULT_OK) {
            FinalProcess finalProcessReturn = (FinalProcess) data.getSerializableExtra("FinalProcessReturn");
            if (finalProcessReturn == null) {
                Intent intent = getIntent();
                intent.putExtra("FinalProcessReturn", finalProcessReturn);
                setResult(RESULT_OK, intent);
                finish();
                return;
            }
            List<FinalProcess.ItemInfoDTO> trackingCode = finalProcessReturn.getIbLpnItemList();
            if (trackingCode == null) {
                Intent intent = getIntent();
                intent.putExtra("FinalProcessReturn", finalProcessReturn);
                setResult(RESULT_OK, intent);
                finish();
                return;
            }
            if (trackingCode.size() == 0) {
                Intent intent = getIntent();
                setResult(RESULT_OK, intent);
                finish();
                return;
            }
            binding.tvCode.requestFocus();
            binding.tvCode.setText("");
            binding.tvCodeSku.setText("");
            binding.tvQty.setText("0");
            bottomLayoutBinding.tvHint.setText("");
            finalProcessLpnList = trackingCode;
            adapter.setData(finalProcessLpnList, 1);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
